import pickle

data = [1, 2, 3, 4, 5]

# 打开一个文件以写入二进制数据
with open('data/data.pkl', 'wb') as file:
    pickle.dump(data, file)

print("序列化完成")

# 打开文件以读取二进制数据
with open('data/data.pkl', 'rb') as file:
    loaded_data = pickle.load(file)

print("反序列化 %s" % loaded_data)


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person(name='{self.name}', age={self.age})"


# 创建一个自定义对象
person = Person("Alice", 30)

# 序列化并保存到文件
with open('data/person.pkl', 'wb') as file:
    pickle.dump(person, file)

# 从文件中加载并反序列化
with open('data/person.pkl', 'rb') as file:
    loaded_person = pickle.load(file)

print(loaded_person)  # 输出: Person(name='Alice', age=30)
